<template>
  <div class="page">
    <van-divider :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px' }">
      <span class="bc-item" v-for="(name,i) in breadcrumb" :key="i">{{ name }}</span>
    </van-divider>
    <div class="task-list">
      <div class="total-num">已巡检
        <a @click="clickTaskList('0')">{{ finishNum }}</a>
        个设备 ,未巡检
        <a @click="clickTaskList('1')">{{ allNum - finishNum }}</a>
        个设备 ,共计
        <a @click="clickTaskList('2')">{{ allNum }}</a>
        个设备</div>
      <div v-for="item in showTaskList" :key="item.id" class="task-content">
        <div class="task-list-item">
          <img src="~@/assets/imgs/publicline/index/icon_device.png" alt="" />
          <div class="task-item-info">
            <div class="item-info mgl8">
              <div class="head">
                <span class="name">{{ item.deviceName }}</span>
                <span class="sub-name mgl8">{{ item.deviceId }}</span>
                <span class="sub-name mgl8" v-if="item.inspectionResult === '1'">正确</span>
                <span class="sub-name mgl8" v-if="item.inspectionResult === '2'">已修改</span>
                <span class="sub-name mgl8" v-if="item.inspectionResult === '3'">无设备</span>
                <span class="sub-name mgl8" style="border:1px solid #07c160; color: #07c160" v-if="item.flag === '1'">新增</span>
                <span v-if="!finishFlag" class="mgr8" @click="deleteDevice(item.id)"><van-icon name="cross" /></span>
              </div>
              <div class="sub-title">地址：{{ item.deviceAddr }}</div>
              <div class="sub-title" v-if="item.inspectionResult === '2'">修改后地址：{{ item.changeAddr }}</div>
            </div>
          </div>
        </div>
        <div class="task-opera">
          <van-uploader
            v-model="pictureList[item.id]"
            upload-text="设备图片"
            :max-count="1"
            :before-delete="() => beforeDelete(item.id)"
            :before-read="beforeRead"
            :after-read="(file) => afterUpload(file, item.id)"
          />
          <div v-if="finishFlag">
            <div style="margin: 16px; text-align: center">
              <div class="form-btn disabled" >当前小区任务已完成</div>
            </div>
          </div>
          <div v-else>
            <van-tag type="primary" size="large" @click="deviceCheck('1', item.id, '')">
              <van-icon name="success" />
            </van-tag>
            <van-tag type="warning" size="large" class="mgl8" @click="changeAddr(item)">
              <van-icon name="edit" />
            </van-tag>
            <van-tag type="danger" size="large" class="mgl8" @click="deviceCheck('3', item.id, '')">
              <van-icon name="cross" />
            </van-tag>
          </div>
        </div>
      </div>

      <div v-if="!finishFlag" style="text-align: center; position: fixed; left: 75%; right: 10%; bottom: 10%">
        <van-button round type="info" @click="addDevice()"><van-icon name="plus" size="20"/></van-button>
      </div>

      <van-dialog class="task-info" v-model="isShowDia" :title="`设备巡检-${curTask.deviceName}`" show-cancel-button :before-close="onBeforeClose" @cancel="handleCancel" @confirm="handleConfirm">
        <van-field autosize type="textarea" v-model="deviceAddr" label="设备地址" required  placeholder="请输入设备地址" />
        <span></span>
      </van-dialog>
      <van-dialog class="task-info" v-model="isAddDia" title="添加巡检设备" show-cancel-button @cancel="addCancel" @confirm="addConfirm">
        <van-field autosize v-model="addData.deviceId" label="设备ID" required  placeholder="请输入设备ID"/>
        <van-field autosize v-model="addData.deviceName" label="设备名称" required  placeholder="请输入设备名称" />
        <van-field autosize type="textarea" v-model="addData.deviceAddr" label="设备地址" required  placeholder="请输入设备地址" />
<!--        <van-field-->
<!--          required-->
<!--          label="设备图片"-->
<!--          :rules="[{ required: true, message: '请上传设备图片' }]"-->
<!--        >-->
<!--          <template #input>-->
<!--            <van-uploader-->
<!--              v-model="newPicture"-->
<!--              upload-text="设备图片"-->
<!--              :max-count="1"-->
<!--              :before-read="beforeRead"-->
<!--              :after-read="(file) => afterUpload(file)"-->
<!--            />-->
<!--          </template>-->
<!--        </van-field>-->
      </van-dialog>

    </div>
  </div>
</template>

<script>
import {addWysb, deleteWysb, getCommunityInfo, saveWysb, wysbTaskList} from '@/api/publicline/kdcs'
import {Dialog, Toast} from 'vant'
import {geometry, getCurrentLocation} from "@/utils/geo";
import {compressImage, setFileRequestToken} from "@/utils/wyy";
import {uploadCos} from "@api/common";

export default {
  data() {
    return {
      finishFlag: false,
      activePage: '1',
      showTaskList: [],
      breadcrumb: [],
      taskList: {
        finishList: [],
        noFinishList: [],
        allList: []
      },
      allNum: 0,
      finishNum: 0,
      isShowDia: false,
      isAddDia: false,
      curTask: {},
      deviceAddr: '',
      addData: {
        deviceName: '',
        deviceId: '',
        deviceAddr: ''
      },
      communityInfo: {},
      newPicture: [],
      pictureList: {}
    }
  },
  created() {
    const { communityId, breadcrumb, buildId } = this.$route.query;
    this.communityId = communityId;
    this.breadcrumb = breadcrumb.split('/');
    this.buildId = buildId
    this.getCommunityInfo()

    getCurrentLocation( (info) => {
      this.currentLocation = info;
    }, () => {
      Toast.fail("当前定位获取失败")
    } )
  },
  methods: {
    getCommunityInfo() {
      getCommunityInfo( { VILLAGE_ID: this.communityId } )
        .then( res => {
          if ( res.success ) {
            const data = res.result.data;
            this.communityInfo = data;
            this.communityInfo.xqwl = JSON.parse(data.xqwl);
            if(data.state === '2') {
              this.finishFlag = true
            }

            this.getTaskList();
          }
        } )
    },
    getTaskList() {
      wysbTaskList( { villageId: this.communityId, buildId: this.buildId } )
        .then( res => {
          if ( res.success ) {
            const data = res.result;
            this.taskList.allList = []
            this.taskList.finishList = []
            this.taskList.noFinishList = []
            for (const index in data) {
              const task = data[index]
              const pictureUrl = task.pictureUrl
              const id = task.id
              if(pictureUrl != null && pictureUrl !== '' && pictureUrl !== undefined) {
                this.pictureList[id] = this.splitImg(pictureUrl)
              }
              this.taskList.allList.push(task)
              if(task.state === '0') {
                this.taskList.noFinishList.push(task)
              }
              if(task.state === '1') {
                this.taskList.finishList.push(task)
              }
            }

            this.allNum = this.taskList.allList.length
            this.finishNum = this.taskList.finishList.length
            this.clickTaskList(this.activePage)
          }
        } )
    },
    viewTask(id, name) {
      this.$router.push( {
        path: "/publicline/kdcs/wysb-list",
        query: {
          communityId: this.communityId,
          buildingId: id,
          buildingName: name,
          breadcrumb: this.breadcrumb.concat([name]).join('/')
        }
      } )
    },
    // 打开增加设备弹窗
    addDevice() {
      this.isAddDia = true
    },
    // 打开修改地址弹窗
    changeAddr(item) {
      this.deviceAddr = item.deviceAddr
      this.curTask = item
      this.isShowDia = true
    },
    // 取消弹窗
    handleCancel() {
      this.isShowDia = false
      this.deviceAddr = ''
      this.curTask = {}
    },
    addCancel() {
      this.isAddDia = false
      this.addData = {
        deviceName: '',
        deviceDzs: '',
        deviceAddr: ''
      }
    },
    // 阻止对话框关闭
    onBeforeClose (action, done) {
      if (action === "confirm") {
        return done(false)
      } else {
        return done()
      }
    },
    deleteDevice(id) {
      const param = {
        id: id,
        LOCATION: this.currentLocation
      }

      Dialog.confirm({
        title: '操作确认',
        message: '确认删除该设备？',
      })
        .then(() => {
          // on confirm
          deleteWysb( param )
            .then( res => {
              if ( res.success ) {
                Toast.success("设备删除成功")
                this.getTaskList();
              }
            } )
        })
        .catch(() => {
          // on cancel
        })
    },
    addConfirm() {
      const aaaa = this.newPicture
      const center = this.currentLocation
      let xqwl = []
      for ( const item of this.communityInfo.xqwl ) {
        xqwl.push( item.join(',') )
      }
      xqwl = xqwl.join(';')
      geometry(xqwl, center, 'distance', (distance) => {
        if ( distance < 100 ) {
          this.addData = {
            ...this.addData,
            villageId: this.communityId,
            buildId: this.buildId,
            LOCATION: this.currentLocation,
            state: '1',
            flag: '1'
          }
          if ( this.addData.deviceId === '' || this.addData.deviceId === undefined || this.addData.deviceId === null ) {
            Toast.fail("请输入设备ID")
            return;
          }
          if ( this.addData.deviceName === '' || this.addData.deviceName === undefined || this.addData.deviceName === null ) {
            Toast.fail("请输入设备名称")
            return;
          }
          if ( this.addData.deviceAddr === '' || this.addData.deviceAddr === undefined || this.addData.deviceAddr === null ) {
            Toast.fail("请输入设备地址")
            return;
          }

          const param = {
            deviceId: this.addData.deviceId
          }
          wysbTaskList(param).then( res => {
            if ( res.success ) {
              const data = res.result;
              if(data.length > 0) {
                Toast.fail("已存在相同ID的设备")
                return;
              } else {
                addWysb( this.addData )
                  .then( res => {
                    if ( res.success ) {
                      Toast.success("设备新增成功")
                      this.addData = {
                        deviceName: '',
                        deviceId: '',
                        deviceAddr: ''
                      }
                      this.getTaskList();
                    }
                  } )
              }
            }
          })
        } else {
          Toast.fail('未到达小区范围，不允许提交结果');
        }
      })
    },
    // 确定
    handleConfirm() {
      if(this.deviceAddr === '') {
        Toast('请输入设备地址')
        return false
      } else {
        this.deviceCheck('2', this.curTask.id, this.deviceAddr)
        this.isShowDia = false
      }
    },
    deviceCheck(type, id, newAddr) {
      const center = this.currentLocation;
      let xqwl = [];
      for ( const item of this.communityInfo.xqwl ) {
        xqwl.push( item.join(',') );
      }
      xqwl = xqwl.join(';');
      geometry(xqwl, center, 'distance', (distance) => {
        if ( distance < 100 ) {
          const pictureUrl = this.pictureList[id]
          if(pictureUrl == null || pictureUrl === '' || pictureUrl === undefined || pictureUrl.length === 0) {
            Toast.fail("请上传设备图片!")
            return;
          }
          const param = {
            id: id,
            pictureUrl: pictureUrl[0].sourceUrl,
            inspectionResult: type,
            changeAddr: newAddr,
            LOCATION: this.currentLocation
          }
          saveWysb(param)
            .then( res => {
              if ( res.success ) {
                Toast.success('操作成功');
                this.getTaskList();
              }
            } )
        } else {
          Toast.fail('未到达小区范围，不允许提交结果');
          return
        }
      })
    },
    clickTaskList(type) {
      this.activePage = type
      switch (type) {
        case '0':
          this.showTaskList = this.taskList.finishList
          break
        case '1':
          this.showTaskList = this.taskList.noFinishList
          break
        case '2':
          this.showTaskList = this.taskList.allList
          break
      }
    },
    beforeRead(file) {
      if (file.type === 'image/jpeg' || file.type === 'image/png') {
        return compressImage(file);
      }
      Toast('请上传 jpg、png 格式图片')
      return false
    },
    beforeDelete(picId) {
      this.pictureList[picId] = []
      this.flashData(picId)
    },
    flashData(picId) {
      let finishList = []
      for(const item in  this.taskList.finishList) {
        const id = this.taskList.finishList[item].id
        let data = this.taskList.finishList[item]
        if(id === picId) {
          data.pictureUrl = ''
        }
        finishList.push(data)
      }
      this.taskList.finishList = finishList

      let noFinishList = []
      for(const item in  this.taskList.noFinishList) {
        const id = this.taskList.noFinishList[item].id
        let data = this.taskList.noFinishList[item]
        if(id === picId) {
          data.pictureUrl = ''
        }
        noFinishList.push(data)
      }
      this.taskList.noFinishList = noFinishList

      let allList = []
      for(const item in  this.taskList.allList) {
        const id = this.taskList.allList[item].id
        let data = this.taskList.allList[item]
        if(id === picId) {
          data.pictureUrl = ''
        }
        allList.push(data)
      }
      this.taskList.allList = allList

      switch (this.activePage) {
        case '0':
          this.showTaskList = this.taskList.finishList
          break
        case '1':
          this.showTaskList = this.taskList.noFinishList
          break
        case '2':
          this.showTaskList = this.taskList.allList
          break
      }
    },
    async afterUpload(file, picId) {
      console.log("开始上传");
      file.status = 'uploading'
      file.message = '上传中...'

      console.log(file)
      const formData = new FormData()
      formData.append('file', file.file)
      formData.append('biz', 'wgyyXccs')
      formData.append('permission', 'public')
      const res = await uploadCos(formData)
      if (res.success) {
        const message = res.message.split('|')
        const newPath = message[0]
        const md5 = message[1]

        file.url = newPath
        file.md5 = md5
        file.sourceUrl = newPath
        file.status = 'success'
        file.message = '上传成功'
        console.log(file)
      } else {
        file.status = 'failed'
        file.message = res.message
      }
      this.flashData(picId)
    },
    splitImg(img) {
      return img.split(',').map((item, index) => {
        return {
          url: setFileRequestToken(item),
          sourceUrl: item
        };
      });
    }
  }
}
</script>

<style lang="less" scoped>
.page {
  background: #FFF;
  .bc-item {
    &:after {
      content: "-";
    }
    &:last-child::after {
      content: "";
    }
  }
  .form-btn {
    padding: 10px 10px;
    border-radius: 20px;
    background: #008cff;
    color: #FFF;

    &.danger {
      background: #ff3700;
      color: #FFF;
    }
  }
}
.task-list {
  padding: 0 12px;
  .total-num {
    padding-bottom: 4px;
    font-size: 12px;
    color: #666;
    text-align: right;

    a {
      color: #0c85ff;
      font-width: bold;
      text-decoration: underline;
    }
  }
  .mgl8 {
    margin-left: 8px;
  }
  .mgr8 {
    margin-right: 8px;
    float: right;
    color: #ee0a24;
    border: 1px solid red;
    border-radius: 8px 3px 8px 3px;
    font-size: 12px;
    line-height: 12px;
    padding: 2px 6px 0;
  }
  .task-content {
    background: #FFF;
    box-shadow: 0 2px 4px 1px #F3F7FA;
    border-radius: 6px;
    padding: 12px 8px;
    margin-bottom: 8px;
  }
  .task-list-item {
    display: flex;
    align-items: flex-start;
    justify-content: flex-start;
    > img {
      width: 28px;
    }
  }
  .task-item-info {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    flex: 1;
    .sub-name {
      border: 1px solid #4D98FF;
      border-radius: 3px 8px 3px 8px;
      color: #4D98FF;
      font-size: 12px;
      line-height: 12px;
      padding: 2px 6px 0;
    }
  }
  .item-info {
    flex: 1;
    .title {
      color: #333334;
      font-size: 14px;
      padding-bottom: 2px;
    }
    .sub-title {
      font-size: 12px;
      color: #666;
      letter-spacing: -0.14px;
      padding: 6px 0;
    }
  }
  .task-opera {
    display: flex;
    justify-content: flex-end;
  }
  .van-tag {
    width: 50px;
    justify-content: center;
  }
}
/deep/ .van-dialog__content {
  padding: 12px 0;
}
</style>
